﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.SamllPicPrint.View;
using MINERP.MODEL.SmallPic;
using MINERP.BLL.SmallPic;
using MINERP.SamllPicPrint.Forms;
using System.Windows.Forms;
using System.IO;
using MINERP.MODEL.FoundationModel;
using System.Data;
using FastReport;
using FastReport.Utils;
using MINERP.SamllPicPrint.Properties;
using MINERP.COM;

namespace MINERP.SamllPicPrint.Presenter
{
    public class MainPresenter
    {
        private IMainView _view;
        private List<ProductView> _curTaskList;
        private SamllPicMainBLL _bll;

        private Printer_Info _printerInfo = null;

        public MainPresenter(IMainView view)
        {

            _view = view;
            _bll = new SamllPicMainBLL();
            _printerInfo = _bll.GetPrinterObj(_view.PrinterId);
            _view._printerConfigInfo = GetPrinterConfigInfo(_printerInfo.PrinterID);
            IniFrmView();

        }

        internal void IniFrmView()//初始化界面内容
        {
            int curTechid = _view.CurTechId;
            if (curTechid == 0)
            {
                curTechid = 12;//默认值为12
            }
            if (curTechid != 0)
            {
                _curTaskList = _bll.GetCurTaskList(curTechid, _printerInfo.PrinterID);
                _view.ShowTaskList(_curTaskList);
            }
        }

        internal void ExPortPic()//导出照片到指定的目录
        {

            string strDir = _printerInfo.HotDirPath;
            if (string.IsNullOrEmpty(strDir))
            {
                MessageBox.Show("没有设定扩印机的默认文件夹，请先设定！");
                return;
            }
            else
            {
                DataTransfer.StrReportDir = strDir;
            }

            if (!Directory.Exists(strDir))
            {
                MessageBox.Show("请确认扩印机的默认文件夹能正常访问，然后再试！");
                return;
            }

            StartExport();
        }

        public delegate void ShowMsg(string photoPath, bool isSus);
        public static event ShowMsg ShowMsgEvent;

        private void StartExport()//开始导出图片
        {
            if (_curTaskList == null)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }
            List<ProductView> selectProduct = _curTaskList.Where(o => o.IsSelect).ToList();
            if (selectProduct.Count < 1)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }

            FrmMovePic frmMsg = new FrmMovePic();
            frmMsg.TotalPhotoNum = selectProduct.Sum(o => o.Photos.Count);
            frmMsg.Show();

            foreach (var oiTask in selectProduct)
            {
                string strTarGetOrderPath = DataTransfer.StrReportDir + "\\" + oiTask.OrderCode + "_" + oiTask.ShopName+"_" + oiTask.CtmName  + "_" + oiTask.OrderName;
                if (!Directory.Exists(strTarGetOrderPath))
                {
                    Directory.CreateDirectory(strTarGetOrderPath);

                }
                else
                {
                    if (DialogResult.No == MessageBox.Show("该定单产品的目录已存在是否要覆盖？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {
                        continue;
                    }
                }

                //然后移图片
                bool CopyOk = MovePic(oiTask, strTarGetOrderPath);
                oiTask.Status = 1;
                if (CopyOk)
                {
                    if (_view._printerConfigInfo.IsAutoPrintTikect)
                    {
                        //PrintOItask(oiTask);
                        PrintTicket(_bll.GetOrderInfoToPrintTicket(oiTask.OrderProductId, _printerInfo.PrinterID, Properties.Settings.Default.IsAssignGrid));
                    }
                }

            }
            //frmMsg.Close();
            MessageBox.Show("导出成功！");
        }

        private bool MovePic(ProductView curProudct, string tarGetPath)//当sourPath中的照片移动到tarGetPath目录中，只包括一层的jpg.tif
        {
            bool result = true;
            //foreach (var photo in curProudct.Photos)
            //{
            //    if (!DataTransfer.AutoRecoverPath)
            //    {
            //        FileInfo fi = new FileInfo(photo.PicPath);
            //        try
            //        {
            //            fi.CopyTo(tarGetPath + "\\" + fi.Name, true);
            //            string newName = fi.Name.Substring(0, fi.Name.IndexOf(fi.Extension));
            //            if (DataTransfer.MoveByPhotoNum)
            //            {
            //                for (int i = 1; i < photo.TotalNum * curProudct.OrderNum; i++)
            //                {
            //                    fi.CopyTo(tarGetPath + "\\" + newName + i.ToString() + fi.Extension, true);
            //                }
            //            }
            //        }
            //        catch (Exception)
            //        {
            //            ShowMsgEvent(photo.PicPath, false);
            //            MessageBox.Show("移动图片" + fi.FullName + "时出错，请手动拷贝!");
            //            result = false;

            //            break;
            //        }
            //        ShowMsgEvent(photo.PicPath, true);
            //    }
            //    else
            //    {
            //        string secondDirPath="";
            //        if (photo.Remark.IndexOf("\\") > 0)
            //        {
            //            secondDirPath = photo.Remark.Substring(0, photo.Remark.LastIndexOf("\\"));
            //        }
            //        string strPhotoDirPath = tarGetPath + "\\" + secondDirPath + "\\";
            //        if (!Directory.Exists(strPhotoDirPath))
            //        {
            //            Directory.CreateDirectory(strPhotoDirPath);
            //        }
            //        string PhotoPath = strPhotoDirPath + photo.PicPath.Substring(photo.PicPath.LastIndexOf("\\") + 1);
            //        FileInfo fi = new FileInfo(photo.PicPath);

            //        try
            //        {
            //            fi.CopyTo(PhotoPath, true);
            //            string newName = fi.Name.Substring(0, fi.Name.IndexOf(fi.Extension));
            //            if (DataTransfer.MoveByPhotoNum)
            //            {
            //                for (int i = 1; i < photo.TotalNum * curProudct.OrderNum; i++)
            //                {
            //                    fi.CopyTo(tarGetPath + "\\" + newName + i.ToString() + fi.Extension, true);
            //                }
            //            }
            //        }
            //        catch (Exception)
            //        {
            //            ShowMsgEvent(photo.PicPath, false);
            //            MessageBox.Show("移动图片" + fi.FullName + "时出错，请手动拷贝!");
            //            result = false;

            //            break;
            //        }
            //        ShowMsgEvent(photo.PicPath, true);
            //    }

            //
            int iNum = 0;
            if (DataTransfer.MoveByPhotoNum)
            {
                foreach (var photo in curProudct.Photos)
                {

                    if (!DataTransfer.AutoRecoverPath)
                    {
                        FileInfo fi = new FileInfo(photo.PicPath);
                        try
                        {


                            string tarFileName = tarGetPath + "\\" + fi.Name;

                            if (File.Exists(tarFileName))
                            {
                                string fileName = fi.Name.Substring(0, fi.Name.LastIndexOf("."));
                                string fileExtend = fi.Name.Substring(fi.Name.LastIndexOf("."));
                                iNum++;
                                fi.CopyTo(tarGetPath + "\\" + fileName + "_" + (iNum + 1) + fileExtend, true);
                            }
                            else
                            {
                                fi.CopyTo(tarFileName, true);
                            }


                            //string newName = fi.Name.Substring(0, fi.Name.IndexOf(fi.Extension));


                            //    for (int i = 1; i < photo.TotalNum * curProudct.OrderNum; i++)
                            //    {
                            //        fi.CopyTo(tarGetPath + "\\" + newName + i.ToString() + fi.Extension, true);

                            //}
                        }
                        catch (Exception)
                        {
                            ShowMsgEvent(photo.PicPath, false);
                            MessageBox.Show("移动图片" + fi.FullName + "时出错，请手动拷贝!");
                            result = false;

                            break;
                        }
                        ShowMsgEvent(photo.PicPath, true);
                    }
                    else
                    {
                        string secondDirPath = "";
                        if (photo.Remark.IndexOf("\\") > 0)
                        {
                            secondDirPath = photo.Remark.Substring(0, photo.Remark.LastIndexOf("\\"));
                        }
                        string strPhotoDirPath = tarGetPath + "\\" + secondDirPath + "\\";
                        if (!Directory.Exists(strPhotoDirPath))
                        {
                            Directory.CreateDirectory(strPhotoDirPath);
                        }
                        string PhotoPath = strPhotoDirPath + photo.PicPath.Substring(photo.PicPath.LastIndexOf("\\") + 1);
                        FileInfo fi = new FileInfo(photo.PicPath);

                        try
                        {
                            string tarFileName = strPhotoDirPath + "\\" + fi.Name;
                            if (File.Exists(tarFileName))
                            {
                                string fileName = fi.Name.Substring(0, fi.Name.LastIndexOf("."));
                                string fileExtend = fi.Name.Substring(fi.Name.LastIndexOf("."));
                                iNum++;
                                fi.CopyTo(strPhotoDirPath + "\\" + fileName + "_" + (iNum + 1) + fileExtend, true);
                            }
                            else
                            {
                                fi.CopyTo(tarFileName, true);
                            }

                        }
                        catch (Exception)
                        {
                            ShowMsgEvent(photo.PicPath, false);
                            MessageBox.Show("移动图片" + fi.FullName + "时出错，请手动拷贝!");
                            result = false;

                            break;
                        }
                        ShowMsgEvent(photo.PicPath, true);
                    }
                }
            }
            else
            {
                foreach (var photo in curProudct.Photos.GroupBy(ph => ph.PicPath))
                {
                    if (!DataTransfer.AutoRecoverPath)
                    {
                        FileInfo fi = new FileInfo(photo.Key);
                        try
                        {
                            fi.CopyTo(tarGetPath + "\\" + fi.Name, true);
                            string newName = fi.Name.Substring(0, fi.Name.IndexOf(fi.Extension));

                        }
                        catch (Exception)
                        {
                            ShowMsgEvent(photo.Key, false);
                            MessageBox.Show("移动图片" + fi.FullName + "时出错，请手动拷贝!");
                            result = false;

                            break;
                        }
                        ShowMsgEvent(photo.Key, true);
                    }
                    else
                    {
                        string secondDirPath = "";
                        if (photo.FirstOrDefault().Remark.IndexOf("\\") > 0)
                        {
                            secondDirPath = photo.FirstOrDefault().Remark.Substring(0, photo.FirstOrDefault().Remark.LastIndexOf("\\"));
                        }
                        string strPhotoDirPath = tarGetPath + "\\" + secondDirPath + "\\";
                        if (!Directory.Exists(strPhotoDirPath))
                        {
                            Directory.CreateDirectory(strPhotoDirPath);
                        }
                        string PhotoPath = strPhotoDirPath + photo.FirstOrDefault().Remark.Substring(photo.FirstOrDefault().Remark.LastIndexOf("\\") + 1);
                        FileInfo fi = new FileInfo(photo.Key);

                        try
                        {
                            fi.CopyTo(PhotoPath, true);
                            string newName = fi.Name.Substring(0, fi.Name.IndexOf(fi.Extension));
                            if (DataTransfer.MoveByPhotoNum)
                            {
                                for (int i = 1; i < photo.FirstOrDefault().TotalNum * curProudct.OrderNum; i++)
                                {
                                    fi.CopyTo(strPhotoDirPath + "\\" + newName + i.ToString() + fi.Extension, true);
                                }
                            }
                        }
                        catch (Exception)
                        {
                            ShowMsgEvent(photo.Key, false);
                            MessageBox.Show("移动图片" + fi.FullName + "时出错，请手动拷贝!");
                            result = false;

                            break;
                        }
                        ShowMsgEvent(photo.Key, true);
                    }

                }
            }

            return result;
        }

        internal void PrintSelectTask()//打印选定的产品（连打）
        {
            if (_curTaskList == null)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }
            List<ProductView> selectProduct = _curTaskList.Where(o => o.IsSelect).ToList();
            if (selectProduct.Count < 1)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }

            foreach (var oiTask in selectProduct)
            {
                //PrintOItask(oiTask);
                PrintTicket(_bll.GetOrderInfoToPrintTicket(oiTask.OrderProductId, _printerInfo.PrinterID, Properties.Settings.Default.IsAssignGrid));
            }
        }


        internal void CompleteSelectTask()//完成选定的产品列表
        {
            if (_curTaskList == null)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }
            List<ProductView> selectProduct = _curTaskList.Where(o => o.IsSelect).ToList();
            if (selectProduct.Count < 1)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }

            if (DialogResult.Yes == MessageBox.Show("确认要完成选中的产品？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                foreach (var oiTask in selectProduct)
                {
                    if (oiTask.Status != 1)
                    {
                        if (DialogResult.Yes == MessageBox.Show("产品：" + oiTask.OrderPath + "在本此操作中未导出过片，是否要完成?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                        {
                            _bll.CompleteTask(oiTask, _view.CurTechId, _view.OperUid, _printerInfo.PrinterID);
                        }
                        else
                        {
                            continue;
                        }
                    }

                    _bll.CompleteTask(oiTask, _view.CurTechId, _view.OperUid, _printerInfo.PrinterID);

                }

                IniFrmView();
                MessageBox.Show("操作成功！");
            }
        }
        /// <summary>
        /// 打印小票
        /// </summary>
        /// <param name="gInfo"></param>
        public void PrintTicket(MINERP.MODEL.SmallPic.OrderInfo_Info orderInfo)
        {
            try
            {
                Report report = new Report();
                report.Load(Application.StartupPath + "\\Report\\扩印小票.frx");
                //分为二部分：1、照片尺寸归类信息，用TABLE格式
                DataTable dt = new DataTable("PhotoSize");
                dt.Columns.Add("Size", typeof(string));
                dt.Columns.Add("Num", typeof(int));
                if (orderInfo.ProductType == (int)OrderInfoProductType.NeedDesignKuoYin || orderInfo.ProductType == (int)OrderInfoProductType.NoNeedDesignKuoYin)
                {
                    dt.Rows.Add(new object[] { orderInfo.OrderProductName, orderInfo.PhotoInfoList.Count });
                }
                else
                {
                    foreach (var item in orderInfo.PhotoInfoList.GroupBy(p => p.PhtotoSizeInch + "(in) (" + p.PhotoSizeCm + ")cm").ToList())
                    {
                        dt.Rows.Add(new object[] { item.Key, item.Count() });
                    }
                }

                dt.WriteXml(@"C:\WINDOWS\xmldata\扩印小票.xml", XmlWriteMode.WriteSchema);
                //2、相应的头信息

                report.RegisterData(dt, "PhotoSize");
                //dt.WriteXml("");

                //gInfo.OrderInfo.CtmName = gInfo.OrderInfo.CtmName.Replace('[', '(').Replace(']', ')');
                //gInfo.OrderInfo.OrderProductName = gInfo.OrderInfo.OrderProductName.Replace('[', '(').Replace(']', ')');
                //gInfo.OrderInfo.Remark = gInfo.OrderInfo.Remark.Replace('[', '(').Replace(']', ')');

                report.SetParameterValue("shopName", orderInfo.ShopName.Replace('[', '(').Replace(']', ')'));
                report.SetParameterValue("orderBarCode", orderInfo.OrderProductId.ToString().Replace('[', '(').Replace(']', ')'));
                report.SetParameterValue("ctmName", orderInfo.CtmName.Replace('[', '(').Replace(']', ')'));
                report.SetParameterValue("orderProductName", orderInfo.OrderProductName.Replace('[', '(').Replace(']', ')'));
                //fasrReport.SetParameterValue("nextTechName", nextTechName);
                report.SetParameterValue("orderRemark", orderInfo.Remark.Replace('[', '(').Replace(']', ')'));
                //fasrReport.SetParameterValue("gridName", gInfo.GridBaseInfo.GridName);
                report.SetParameterValue("priorityRemark", orderInfo.Priority >= 6 ? "急件" + orderInfo.Priority.ToString() : "");
                report.SetParameterValue("photoNumAndTotalNum", orderInfo.PhotoNumAndTotalNum);
                report.SetParameterValue("PaperTypeName", orderInfo.PaperTypeName);
                report.SetParameterValue("NextTech", orderInfo.NextTech);
                report.SetParameterValue("ShopGridName", orderInfo.ShopGridName);
                report.SetParameterValue("PaperFaceName", orderInfo.PaperFaceName);
                report.SetParameterValue("ProductOrderInBag", orderInfo.ProductOrderInBag);
                report.SetParameterValue("ProductCaName", orderInfo.ProductCaName);
                report.SetParameterValue("OrderTime", orderInfo.OrderTime);
                report.SetParameterValue("FetchTime", orderInfo.FetchTime);
                if (Properties.Settings.Default.PrintDialog)
                {
                    report.PrintSettings.ShowDialog = true;
                }
                else
                {
                    report.PrintSettings.ShowDialog = false;
                }

                report.Print();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        internal void FullSelect()
        {
            if (_curTaskList != null && _curTaskList.Count > 0)
            {
                _curTaskList.ForEach(t => t.IsSelect = true);
            }
            _view.ShowTaskList(_curTaskList);
        }

        internal void ReSelect()
        {
            if (_curTaskList != null && _curTaskList.Count > 0)
            {
                _curTaskList.ForEach(t => t.IsSelect = !t.IsSelect);
            }
            _view.ShowTaskList(_curTaskList);
        }

        internal int PrintOrderInfo(string strCode)
        {
            int ret = 0;
            ProductView pv = _bll.GetProductViewByCode(strCode);
            if (pv != null)
            {
                //PrintOItask(pv);
                PrintTicket(_bll.GetOrderInfoToPrintTicket(pv.OrderProductId, _printerInfo.PrinterID, Properties.Settings.Default.IsAssignGrid));
            }
            else
            {
                MessageBox.Show("错误的产品编号！");
                ret = 1;
            }
            return ret;
        }


        internal Printer_Info GetPrinterInfo(int printerId)
        {
            return _bll.GetPrinterObj(printerId);
        }

        private PrinterConfigInfo GetPrinterConfigInfo(int printerId)
        {
            PrintConfigBLL bll = new PrintConfigBLL();
            return bll.GetPrinterConfigInfo(printerId);
        }
    }
}
